package org.foucser.traccy;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.Range;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

@SuppressWarnings("serial")
public class TraccyServlet extends AbstractRobotServlet {

	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();

		if (bundle.wasSelfAdded()) {
			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.append("I'm alive!");
		}

		Pattern ptn = Pattern.compile("#[0-9]+");
		for (Event e: bundle.getEvents()) {
			if (e.getType() == EventType.BLIP_SUBMITTED) {
				TextView doc = e.getBlip().getDocument();
				String text = doc.getText();
				Matcher matcher = ptn.matcher(text);
				while (matcher.find()) {
					int start = matcher.start();
					int end = matcher.end();
					Range range = new Range(start, end);
					String ticketNo = text.substring(start+1, end);
					String link = "http://dev.ikamobile.com/projects/movieFinder/ticket/"+ticketNo;
					doc.setAnnotation(range , "link/manual", link);
				}
			}
		}
	}
}
